import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:riverpod_t/config/response_model.dart';
import 'package:riverpod_t/page/car/data/model/info_model.dart';
import 'package:riverpod_t/page/car/data/repository/car_repository.dart';
import 'package:riverpod_t/page/car/event/car_info_op_event.dart';
import 'package:riverpod_t/page/car/river/car_info_op_river.dart';
import 'package:riverpod_t/page/car/state/car_op_state.dart';
import 'package:riverpod_t/page/car/state/car_state.dart';
import 'package:riverpod_t/until/app_util.dart';
part 'car_list_river.g.dart';

///
/// 典型的列表 -> riverpod 案例
/// 仅负责刷新列表
///

@riverpod
class CarListRiver extends _$CarListRiver {
  /// 初始化请求数据
  @override
  Future<CarState> build() async {
    ref.listen(carInfoOpRiverProvider, _listenOpChange);
    return CarState(list: await _getCarList(1));
  }

  /// 刷新方法
  void refresh({bool isRefresh = false}) async {
    try {
      int page = state.value?.page ?? 1;
      List<InfoModel> list = state.value?.list ?? [];
      bool hasNext = true;
      if (isRefresh) {
        page = 1;
      } else {
        page++;
      }
      List<InfoModel>? moreList = await _getCarList(page);
      if (AppUtil.isNotEmpty(moreList)) {
        if (isRefresh) {
          list.clear();
        }
        list.addAll(moreList);
        if (moreList.length >= 20) {
          hasNext = true;
        } else {
          hasNext = false;
        }
      } else {
        hasNext = false;
      }

      state = AsyncValue.data(CarState(list: list, page: page, hasNext: hasNext));
    } catch (err, stack) {
      state = AsyncValue.error(err, stack);
    }
  }

  /// 监听操作事件,刷新列表
  void _listenOpChange(AsyncValue<CarInfoOpState>? previous, AsyncValue<CarInfoOpState>? next) {
    /// 更新点赞状态
    if (previous?.value?.op is CarInfoNoneOp &&
        next?.value?.op is CarInfoLikeOp &&
        next?.value?.model != null) {
      List<InfoModel>? list = state.value?.list;
      if (AppUtil.isEmpty(list)) return;
      InfoModel? model = next?.value?.model;
      var index = list?.indexWhere((element) => element.id == model?.id);
      if (index! < 0) return;
      InfoModel? selectModel = list![index];
      selectModel.isLike = !selectModel.isLike;
      state = AsyncValue.data(CarState(list: list));
    }

    /// 删除数据
    if (previous?.value?.op is CarInfoNoneOp &&
        next?.value?.op is CarInfoRemoveOp &&
        next?.value?.model != null) {
      List<InfoModel>? list = state.value?.list;
      if (AppUtil.isEmpty(list)) return;
      list!.removeWhere((element) => element.id == next?.value?.model?.id);
      state = AsyncValue.data(CarState(list: list));
    }
  }

  Future<List<InfoModel>> _getCarList(int page) async {
    ResponseModel model = await CarRepository.getInfoListData<InfoListModel>(page);
    InfoListModel infoListModel = model.data;
    return infoListModel.works;
  }
}
